// pages/my/login/home/goodsDetail/index.js
const app = getApp()
const {
  navBarHeight,
  statusBarHeight,
  menuButton
} = app.globalData
const {
  baseURL
} = require('../../../fetch/http')
const api = require('../../../fetch/api')
const {
  wxml,
  style
} = require('./demo.js')


Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseURL: baseURL,
    statusBarHeight: statusBarHeight,
    h: navBarHeight,
    w: menuButton.width,
    right: menuButton.right,
    bottomHeight: navBarHeight - statusBarHeight,
    spec: [],
    num: 1,
    index: 0, // 轮播图片下标
    selectedIndex: 0,
    show: false,
    showBottom: false,
    showModal: false,
  },
  reduce() {
    let {
      num
    } = this.data
    num > 1 && num--
    this.setData({
      num
    })
  },
  add() {
    let {
      num,
      spec,
      selectedIndex
    } = this.data
    num < spec[selectedIndex].sku && num++
    this.setData({
      num
    })
  },
  choose(e) {
    const {
      index
    } = app.dataSet(e)
    this.setData({
      selectedIndex: index,
      num: 1
    })
  },
  close() {
    this.setData({
      show: false,
      showBottom: false
    })
  },
  show() {
    this.setData({
      show: true
    })
  },
  closeModal() {
    this.setData({
      showModal: false
    })
  },
  showModal() {
    this.setData({
      showModal: true
    })
  },
  async renderToCanvas() {
    let {
      goods,
      spec,
      selectedIndex,
      headimg,
      nickname,
      code
    } = this.data
    let item = spec[selectedIndex]
    let {
      price,
      linePrice
    } = item
    let {
      goodsName,
      cover
    } = goods
    if (!nickname) {
      app.toast('请登录')
      return
    }

    let text1 = goodsName.slice(0, 7)
    let text2 = goodsName.slice(7, 15)
    let text3 = goodsName.slice(15, 23)
    let text4 = goodsName.slice(23, 31)
    let text5 = goodsName.slice(31, 39)

    const wxml = `
    <view class="top">
    <image class="share_bg" src="https://yd.soft.haoyangsoft.com/static/wx/img/poster_bg.png"></image>
    <image class="avatar" src="${headimg}"></image>
    <text class="nickname">
    来自${nickname}的分享
    </text>
    <image class="qrcode" src="${code}"></image>
    <image class="cover" src="${cover}"></image>
    <text class="name">${text1}</text>
    <text class="text2">${text2}</text>
    <text class="text3">${text3}</text>
    <text class="text4">${text4}</text>
    <text class="text5">${text5}</text>

    <text class="newprice">￥${price}</text>
    <text class="oldprice">￥${linePrice}</text>
    <view class="line"></view>
    <text class="longtap">长按识别二维码<text>
    `
    this.setData({
      show: true
    }, () => {
      this.widget = this.selectComponent('.widget')
      wx.showLoading({
        title: '正在生成海报'
      })
      setTimeout(() => {
        const p1 = this.widget.renderToCanvas({
          wxml,
          style
        })
        p1.then((res) => {
          /* console.log('container', res.layoutBox) */
          this.container = res
          wx.hideLoading()
          this.setData({
            showBottom: true
          })
        })
      }, 500)
    })
  },
  saveImage() {
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      console.log(res);
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: (res) => {
          this.close()
          app.toast('保存成功', 'success')
        }
      })
    })
  },
  goBack() {
    let routers = getCurrentPages()
    if (routers[routers.length - 2]) {
      wx.navigateBack()
    } else {
      wx.switchTab({
        url: '/index/index',
      })
    }
  },
  swiperChange(e) {
    let {
      current
    } = e.detail
    this.setData({
      index: current
    })
  },
  async goodsDetail() {
    let res = await api.goodsDetail({
      goods_id: this.data.id
    })
    this.setData({
      goods: res.data,
      spec: res.data.spec,
      rich: res.data.detail.replace(/\<img/gi, '<img class="rich" style="width:100%;height:auto"')
    })
    // console.log(res);
  },
  async buy() {
    if (!wx.getStorageSync('token')) {
      wx.navigateTo({
        url: '/pages/my/login/login',
      })
      return
    }else{
      if(this.data.goods.goodsType==1){
        this.showModal()
      }else{
        let {
          goods,
          num
        } = this.data
        wx.navigateTo({
          url: `/pages/home/submit/index?gid=${goods.id}&num=${1}`,
        })
      }
    }
    
  },
  async confirm() {
    let {
      goods,
      spec,
      selectedIndex,
      num
    } = this.data
    /* app.globalData.goods = goods
    app.globalData.spec = spec[selectedIndex] */

    wx.navigateTo({
      url: `/pages/home/submit/index?id=${spec[selectedIndex].id}&num=${num}`,
    })
  },
  async userinfo() {
    let res = await api.userinfo()
    this.setData({
      firstDeal: res.data.firstDeal,
      headimg: res.data.headimg,
      nickname: res.data.nickname
    })
  },
  async code() {
    let res = await api.poster()
    this.setData({
      code: res.data
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.userId) {
      wx.setStorageSync('recommend', options.userId)
    }
    this.setData({
      id: options.id // 商品id
    })
    this.goodsDetail()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.getStorageSync('token') && this.userinfo()
    this.code()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
      this.close()
    }
    let userId = wx.getStorageSync('id')
    return {
      imageUrl:  this.data.goods.images[0],
      title: '天喜鑫宝',
      path: `/pages/home/goodsDetail/index?userId=${userId}&id=${this.data.id}`
    }
  }
})